import {getDicts} from "../../api/common";

const app = getApp();
const globalData = app.globalData;
const {config, colorOption, windowInfo, curDept} = globalData;
import {getUserList} from "../../api/um";

Page({
  /**
   * 页面的初始数据
   */
  data: {
    config,
    curDept,
    colorOption,
    windowInfo,
    popupHeight: 0,
    // 分页参数
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      totalRow: 0,
      attrQueryMap: {}
    },
    showAuth: false,
    authStatus: 0,
    // 用户信息列表
    userList: [],
    // 字典Map
    dictMap: {
      XB: {
        title: "性别",
        key: "XB",
        columns: [
          {label: "男", value: 1,},
          {label: "女", value: 2,},
        ],
      },
      NL: {
        title: "年龄",
        key: "NL",
        columns: [
          {label: "20-25", value: '20-25',},
          {label: "26-30", value: '26-30',},
          {label: "31-35", value: '31-35',},
          {label: "36-40", value: '36-40',},
          {label: "41-50", value: '41-50',},
          {label: "51以上", value: '51-999',},
        ],
      },
      SG: {
        title: "身高(CM)",
        key: "SG",
        columns: [
          {label: "150以下", value: '0-150',},
          {label: "151-155", value: '151-155',},
          {label: "156-160", value: '156-160',},
          {label: "161-165", value: '161-165',},
          {label: "166-170", value: '166-170',},
          {label: "171-175", value: '171-175',},
          {label: "176-180", value: '176-180',},
          {label: "181以上", value: '181-999',},
        ],
      },
      TZ: {
        title: "体重(KG)",
        key: "TZ",
        columns: [
          {label: "50以下", value: '0-50',},
          {label: "51-55", value: '51-55',},
          {label: "56-60", value: '56-60',},
          {label: "61-65", value: '61-65',},
          {label: "66-70", value: '66-70',},
          {label: "71-75", value: '71-75',},
          {label: "76-80", value: '76-80',},
          {label: "80以上", value: '80-999',},
        ],
      },

    },
    // 当前字典
    curDict: {},
    // 显示加载中
    isLoading: true,
    // 展开筛选
    openFilter: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 选择地区组件
    this.setData({
      popupHeight: (windowInfo.safeArea ? windowInfo.safeArea.bottom : windowInfo.windowHeight) - (windowInfo.tabBarHeight + 8) - (80 + 182) * windowInfo.rpxRatio,
    })
    this.getDicts()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (typeof this.getTabBar === "function" && this.getTabBar()) {
      this.getTabBar().setSelected(1);
    }
    this.setData({
      curDept: globalData.curDept,
    });
    this.onSearch();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  // 获取字典
  getDicts() {
    const {dictMap} = this.data

    const {attrConfMap} = globalData;
    let confList = []
    Object.keys(attrConfMap).forEach(key => {
      confList = confList.concat(attrConfMap[key])
    })
    confList = confList.filter(s => s.isStandard && !s.attrCode.startsWith('condition-'))

    const dictTemp = {}
    const dictTypes = []
    confList.forEach(item => {
      if (item.isStandard && item.dictType) {
        dictTypes.push(item.dictType)
      }
    })

    getDicts({
      data: {
        key: dictTypes.join(",")
      },
      callBack: res => {
        res.data.forEach(dict => {
          if (dictTemp[dict.dictType]) {
            dictTemp[dict.dictType].push(dict)
          } else {
            dictTemp[dict.dictType] = [dict];
          }
        })
        confList.forEach(conf => {
          if (conf.dictType && dictTemp[conf.dictType]) {
            dictMap[conf.attrCode] = {
              title: conf.attrName,
              key: conf.attrCode,
              dictType: conf.dictType,
              columns: dictTemp[conf.dictType].map(item => {
                return {
                  label: item.dictLabel,
                  value: item.dictValue
                }
              }),
            }
          }
        })
        this.setData({
          dictMap
        })
      }
    })
  },
  // 显示字典选择
  getUserList() {
    this.setData({isLoading: true})
    wx.showLoading({title: '加载中',})
    getUserList({
      data: {
        ...this.data.queryParams,
      },
      callBack: (res) => {
        let userList = this.data.queryParams.pageNum === 1 ? [] : this.data.userList
        this.setData({
          'queryParams.totalRow': res.total,
          isLoading: false,
          userList: userList.concat(res.rows.map(item => {
            item.attrDataMap.TX = item.attrDataMap.TX ? config.localImgSrc + item.attrDataMap.TX : (item.attrDataMap.XB == 1 ? '/images/mine/defaultAvatar_male.png' : '/images/mine/defaultAvatar_female.png');
            return item;
          }))
        })
        setTimeout(() => wx.hideLoading(), 200);
        wx.stopPullDownRefresh();
      },
    })
  },
  //  搜索
  onSearch() {
    this.setData({
      'queryParams.totalRow': 0,
      'queryParams.pageNum': 1,
      userList: [],
      isLoading: true,
    })
    this.getUserList()
  },
  onChange(e) {
    this.setData({
      'queryParams.searchValue': e.detail,
    });
  },
  onShowFilter() {
    this.setData({openFilter: true})
  },
  onCloseFilter() {
    this.setData({openFilter: false})
  },

  // 确定筛选值
  clickFilter(e) {
    const {key, item, index} = e.currentTarget.dataset;
    const {attrQueryMap} = this.data.queryParams;
    console.log('clickFilter', key, item)
    item.active = !!!item.active;
    let columns = this.data.dictMap[key].columns;
    columns.forEach((item, itemIndex) => {  // 取消其他选中 只能单选
      if (index === itemIndex) {
        item.active = !item.active
        if (item.active) {
          if (!attrQueryMap[key]) attrQueryMap[key] = []
          attrQueryMap[key].push(item.value)
        } else {
          attrQueryMap[key] = attrQueryMap[key].filter(value => value !== item.value);
        }
      }
    });
    this.setData({
      'queryParams.attrQueryMap': attrQueryMap,
      [`dictMap.${key}.columns`]: columns,
    })
  },

  // 跳转交友名片页面
  gotoFriendsCard(e) {
    const {item} = e.currentTarget.dataset;
    console.log(item);
    wx.navigateTo({
      url: `/pageA/pages/friends-card/index?id=${item.id}`,
    });
  },
  clearFilter() {
    let dictMap = this.data.dictMap;
    Object.keys(dictMap).forEach(key => {
      dictMap[key].columns.forEach((item, index) => {
        item.active = false;
      });
    })
    this.setData({
      dictMap,
      'queryParams.attrQueryMap': {}
    })
    this.onSearch();
  },
  confirmFilter() {
    this.onSearch();
    this.setData({openFilter: false})
  },

  // 关注按钮
  handleFocus(e) {
    let {id} = e.detail.currentTarget.dataset
    let userList = this.data.userList;
    userList.forEach(item => {
      if (item.id === id) {
        item.isFocus = !item.isFocus;
      }
    })
    this.setData({userList})
  },

  // 选择地区
  handleRegionSelect(e) {
    this.setData({
      curDept: globalData.curDept,
    });
    this.onSearch();
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.onSearch();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    console.log("上拉触底");
    if (this.data.queryParams.totalRow > this.data.userList.length) {
      this.data.queryParams.pageNum++
      this.getUserList()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
  },
  // 认证
  handleAuth(e) {
    this.setData({showAuth: true, authStatus: globalData.userInfo.authStatus})
  },
  handleCloseAuth(){
    this.setData({showAuth: false})
  },
});
